﻿using blackhouse.BlackApart.Business.Opinions;
using blackhouse.mojoPortalExtend.Urls;
using blackhouse.WebNemo.Business.Groups;
using blackhouse.WebNemo.Data.Cache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Web;

namespace blackhouse.StareKino.Web.Navigation {
    public class OpinionUrl {

        #region Fields

        private GroupRecord[] opinionRecords;
        private GroupRecord opinionRecord;
        private IOpinion opinion;

        #endregion

        #region Properties

        private GroupRecord[] OpinionRecords {
            get {
                if (this.opinionRecords == null)
                    this.opinionRecords = this.GetOpinionRecords();
                return this.opinionRecords;
            }
        }

        public bool HaveUrl {
            get { return this.opinionRecord.IsNotNull("url"); }
        }

        #endregion

        #region Constructors

        public OpinionUrl(IOpinion opinion) {
            this.opinion = opinion;
            this.opinionRecord = this.FindOpinionRecord(opinion.Id);
        }

        #endregion

        #region Methods

        private GroupRecord FindOpinionRecord(int opinionId) {
            return this.OpinionRecords.FirstOrDefault(gr => gr.RecordId.Equals(opinionId));
        }

        private GroupRecord[] GetOpinionRecords() {
            GroupRecord[] records = null;
            if (MemoryCache.Default.Contains("opinions"))
                records = (GroupRecord[])MemoryCache.Default["opinions"];
            if (records == null) {
                IGroup opinionGroup = blackhouse.WebNemo.Business.Factory.Instance().GetGroup("OPINIA");
                GroupRecords grs = new GroupRecords(opinionGroup);
                records = grs.GetRecords();
                CacheItem ci = new CacheItem("opinions", records);
                CacheItemPolicy cip = new CacheItemPolicy();
                cip.SlidingExpiration = TimeSpan.FromMinutes(20);
                cip.ChangeMonitors.Add(new NemoChangeMonitor(opinionGroup.Id));
                MemoryCache.Default.Add(ci, cip);
            }
            return records;
        }

        public void CreateUrl() {
            OpinionUrlSupport url = new OpinionUrlSupport(this.opinionRecord, this.opinion);
            UrlSupportProvider urlProvider = new UrlSupportProvider(url);
            urlProvider.Save();
        }

        public string GetUrl() {
            return this.opinionRecord.GetString("url");
        }

        #endregion

    }
}